package tech.lixinlei.feishu.rebot.custom;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;
import tech.lixinlei.feishu.rebot.bo.FeishuRequest;
import tech.lixinlei.feishu.rebot.bo.MessageBody;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

@RestController
public class CustomRobotDemo {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/robot")
    public Object sandMsgToRobot(String key, String msg)
            throws JsonProcessingException {
        HttpHeaders headers = assembleHeader();
        String content = assembleContent(key, msg);
        HttpEntity<String> request = new HttpEntity<>(content, headers);

        String url = "https://open.feishu.cn/open-apis/bot/v2/hook/2700d8bb-032a-4a56-9920-742139c556da";
        ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, request, String.class);

        return postForEntity.getBody();
    }

    private String assembleContent(String key, String msg) {
        FeishuRequest feishuRequest = new FeishuRequest();
        feishuRequest.setMsgType("text");
        feishuRequest.setContent(new MessageBody(msg));
        if (Objects.nonNull(key)) {
            feishuRequest.setSign(generateSign(feishuRequest, key));
        }
        String content = null;
        try {
            content = new ObjectMapper().writeValueAsString(feishuRequest);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }

    private String generateSign(FeishuRequest feishuRequest, String key) {
        Long timestamp = System.currentTimeMillis();
        String signStr = timestamp + "\n" + key;
        String sign = null;
        try {
            Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
            hmacSHA256.init(secret_key);
            byte[] bytes = hmacSHA256.doFinal(signStr.getBytes(Charset.forName("UTF-8")));
            BASE64Encoder encoder = new BASE64Encoder();
            sign = encoder.encode(bytes);
            feishuRequest.setTimestamp(timestamp);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return sign;
    }

    private HttpHeaders assembleHeader() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return headers;
    }

    public static void main(String[] args) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        FeishuRequest feishuRequest = new FeishuRequest();
        feishuRequest.setMsgType("text");
        feishuRequest.setContent(new MessageBody("test message"));

        System.out.println(new ObjectMapper().writeValueAsString(feishuRequest));
    }

}
